package com.android.fitcontrol;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.fitcontrol.bean.Training;
import com.android.fitcontrol.bean.User;
import com.android.fitcontrol.common.CommonUtils;
import com.android.fitcontrol.database.DBConnector;

public class LoginActivity extends Activity{
	private EditText mLoginText;
	private EditText mPasswordText;
	
	private Button mLoginButton;
	private Button mRegisterButton;
	
	private TextView mErrorText;
	
	private DBConnector dbConnector;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_lauout);
		
		mLoginText = (EditText)findViewById(R.id.login);
		mPasswordText = (EditText)findViewById(R.id.password);
		
		mErrorText = (TextView)findViewById(R.id.login_error_message);
		
		mLoginButton = (Button)findViewById(R.id.login_button);
		mRegisterButton = (Button)findViewById(R.id.register_button);
		
		dbConnector = new DBConnector(this);
				
		mLoginButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String login = mLoginText.getText().toString();
				String password = mPasswordText.getText().toString();
				String selection = User.USER_NAME + " = ? and " + User.PASSWORD + " = ?";
				String [] selectionArgs = new String[]{login, password};
				try{
					Cursor c = dbConnector.query(User.TABLE_NAME, null, selection, selectionArgs, null, null, null);
					if(c.moveToFirst()){
						mErrorText.setVisibility(View.INVISIBLE);
						//check training
						Intent exerciseListIntent = new Intent(LoginActivity.this, ExerciseListActivity.class);
						exerciseListIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						Format formatter = new SimpleDateFormat("dd-MM-yyyy");
						Calendar calendar = new GregorianCalendar();
						String dat = calendar.get(Calendar.DAY_OF_MONTH) + "-" + calendar.get(Calendar.MONTH) + "-" + calendar.get(Calendar.YEAR);
						Date resultDate = (Date) formatter.parseObject(dat);
						exerciseListIntent.putExtra("pickedDate", resultDate.getTime());
						String where = Training.USER_ID + " = ? and " + Training.DATE + " = ?";
						String [] args = new String[]{String.valueOf(c.getInt(User.NUM_ID)), String.valueOf(resultDate.getTime())};
						Cursor cur = dbConnector.query(Training.TABLE_NAME, null, where, args, null, null, null);
						boolean isExistTraining = false;
						if(cur.moveToFirst()){
							isExistTraining = true;
							exerciseListIntent.putExtra("training_id", cur.getInt(Training.NUM_ID));
						}
						cur.close();
						//end training check
						//user session
						CommonUtils.createPreloginnedUser(login, password, dbConnector);
						CommonUtils.setUserID(c.getInt(User.NUM_ID));
						//end user session
						if(isExistTraining){
							startActivity(exerciseListIntent);
						}
						else{
							Intent calendarIntent = new Intent(LoginActivity.this, MonthScheduleActivity.class);
							calendarIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							calendarIntent.putExtra("isUp", false);
							startActivity(calendarIntent);
						}
						//CommonUtils.checkPreloginnedUser(LoginActivity.this, dbConnector);
						c.close();
						
					}
					else{
						mErrorText.setTextColor(getResources().getColor(R.color.red));
						mErrorText.setText(R.string.login_error_message);
						mErrorText.setVisibility(View.VISIBLE);
					}
				}
				catch(Exception e){
					e.printStackTrace();
				}
			}
		});
		
		mRegisterButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String login = mLoginText.getText().toString();
				String password = mPasswordText.getText().toString();
				if(login.length() < 2 || password.length() < 2){
					mErrorText.setVisibility(View.VISIBLE);
					mErrorText.setTextColor(getResources().getColor(R.color.red));
					mErrorText.setText(R.string.register_failed_validation);
					return;
				}
				String selection = User.USER_NAME + " = ?";
				String [] selectionArgs = new String[]{login};
				try{
					Cursor c = dbConnector.query(User.TABLE_NAME, null, selection, selectionArgs, null, null, null);
					if(c.moveToFirst()){
						mErrorText.setVisibility(View.VISIBLE);
						mErrorText.setTextColor(getResources().getColor(R.color.red));
						mErrorText.setText(R.string.register_error);
						return;
					}
					else{
						User newUser = new User();
						newUser.setUserName(login);
						newUser.setPassword(password);
						dbConnector.insert(newUser);
						mErrorText.setVisibility(View.VISIBLE);
						mErrorText.setTextColor(getResources().getColor(R.color.green));
						mErrorText.setText(R.string.register_success);
						mLoginText.setText(login);
						mPasswordText.setText(password);
						return;
					}
				}
				catch(Exception e){
					e.printStackTrace();
				}
			}
		});
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		dbConnector.close();
	}
}
